/**
 * axios全局配置
 */
import axios from 'axios'
import config from '../../config'
import qs from 'qs'

/** 请求超时 */
const AXIOS_TIMEOUT = window.g.AXIOS_TIMEOUT
/** 超时设置 */
const service = axios.create({
  // 请求超时时间
  timeout: AXIOS_TIMEOUT
})

/** 调用API接口基本路经 */
const BASE_HTTP_URL = window.g.ApiUrl
console.log('生产APIURL:', BASE_HTTP_URL)

/** 根据环境取URL DEVELOPMENT PRODUCTION */
console.log('环境取值:', process.env.NODE_ENV)
const baseURL = (process.env.NODE_ENV !== 'production' ? config.dev.httpUrl : BASE_HTTP_URL)
console.log('调用API接口基本路经:', baseURL)
service.defaults.baseURL = baseURL

/** 设置默认请求头POST */
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

/**
 * HTTP REQUEST 请求拦截器
 */
service.interceptors.request.use(
  config => {
    console.log('HTTP REQUEST 请求拦截器-CONFIG.METHOD:', config.method)
    if (config.method === 'post') {
      config.data = qs.stringify(config.data)
    }
    if (config.method === 'put') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  err => {
    console.log('HTTP REQUEST 请求拦截器-ERROR:', err)
    return Promise.reject(err)
  }) // END HTTP REQUEST 拦截器

/**
 * HTTP RESPONSE 响应拦截器
 */
service.interceptors.response.use(
  response => response,
  error => {
    console.log('HTTP RESPONSE 响应拦截器ERROR:', error)
    if (error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '错误请求'
          break
        default:
          error.message = `连接错误${error.response.status}`
      }
    } else {
      error.message = '连接到服务器失败'
    }
    return Promise.reject(error.response.data)
  }) // END HTTP RESPONSE 拦截器

/**
 * 请求类型
 *
 * @type {{GET: string, POST: string, PUT: string, DELETE: string}}
 */
const TYPES = {
  GET: 'get',
  POST: 'post',
  PUT: 'put',
  DELETE: 'delete'
}

/**
 * 二次封装AXIOS
 *
 * @param url 请求地址后缀
 * @param data 请求数据
 * @param method [post、get、put、delete] 默认post
 * @returns {Promise<any>}
 */
export const axiosCall = (url, data, method = 'post') => {
  let promise = new Promise(function (resolve, reject) {
    service({
      method: method,
      url: url,
      data: data
    }).then(function (res) {
      resolve(res)
    }).catch(function (err) {
      reject(err)
    })
  })
  return promise
}

/**
 * 提供基本 REST 调用
 */
export default {
  get (url, params) {
    return service({
      url,
      method: 'get',
      params
    })
  },
  post (url, params) {
    return service({
      url,
      method: 'post',
      data: params
    })
  },
  delete (url, params) {
    return service({
      url,
      method: 'delete',
      params
    })
  },
  put (url, params) {
    return service({
      url,
      method: 'put',
      data: params
    })
  },
  service,
  axiosCall,
  TYPES
}
